package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"video-hub/model/cache"
	"video-hub/model/mysql"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *videorpc.UpdatePasswordRequest) (*videorpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.FindUserPhone(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("手机号不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "send"+in.PhoneNum).Result()
	if in.SendSms != result {
		return nil, errors.New("验证码不正确")
	}
	if in.QrPassword != in.NewPassword {
		return nil, errors.New("两次密码不一致")
	}
	user = mysql.User{
		Model:    gorm.Model{ID: user.ID},
		Password: in.NewPassword,
	}
	err = user.UPdatePassword(mysql.DB)
	if err != nil {
		return nil, err
	}
	return &videorpc.UpdatePasswordResponse{
		Msg: "密码已重置成功",
	}, nil
}
